package com.powerbosframework.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


/**
 * XML解析帮助类
 * 
 * @author youfu.wang
 * @version 1.0
 */
public class XMLUtil {

	/**
	 * 解析资源为Document对象
	 * 
	 * @param resource
	 * @return
	 */
	public Document parse(String resource) {
		return this.parse(new File(resource));
	}

	/**
	 * 解析文件为Document对象
	 * 
	 * @param file
	 * @return
	 */
	public Document parse(File file) {
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
		try {
			doc = builder.build(file);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	/**
	 * 解析文件输入流为Document对象
	 * 
	 * @param stream
	 * @return
	 */
	public Document parse(InputStream stream) {
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
		try {
			doc = builder.build(stream);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	/**
	 * 解析url为Document对象
	 * 
	 * @param url
	 * @return
	 */
	public Document parse(URL url) {
		SAXBuilder builder = new SAXBuilder();
		Document doc = null;
		try {
			doc = builder.build(url);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc;
	}

	public Format getFormat() {
		Format format = Format.getPrettyFormat();
		//format.setEncoding("utf-8");
		format.setIndent("  ");
		format.setExpandEmptyElements(false);
		return format;
	}

	public void output(Document doc, String arg1) {
		if (doc == null || arg1 == null)
			return;
		File file = new File(arg1);
		this.output(doc, file);
	}

	public void output(Document doc, File file) {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		try {
			XMLOutputter outputter = new XMLOutputter(getFormat());
			outputter.output(doc, out);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
	}
}
